package com.android.zmusic.musicplay;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;


public class MusicPlayer implements OnCompletionListener, OnErrorListener {
	
	private final String BROCAST_NAME = "com.android.zmusic.musicplay.brocast";
	
	private MediaPlayer mMediaPlayer ;               
	 
	private List<MusicData> mMusicFileList;          //文件列表 

	private int mCurPlayIndex ;                      //当前播放文件index
	
	private int mPlayState ;                          //当前播放状态
	
	private int mPlayMode ;						     //当前播放模式 
	
	private Random mRandom ;
	
	private Context context ;
	
	private void init() {
		mMediaPlayer = new MediaPlayer() ;
		
		mMediaPlayer.setOnCompletionListener(this) ;  
		
		mMediaPlayer.setOnErrorListener(this) ;
		
		mMusicFileList = new ArrayList<MusicData>();
		
		mCurPlayIndex  = -1;
		
		mPlayState = MusicPlayState.MP3_NOFILE;
		
		mPlayMode = MusicPlayMode.MP3_LIST_LOOP_PLAY;
		
	}
	
	
	public MusicPlayer(Context context) {
		
		this.context = context;
		init();
		
		mRandom = new Random();
		mRandom.setSeed(System.currentTimeMillis());
	}
    
	/**
	 * 更新文件列表
	 * @param mMusicFileList
	 */
	public void refreshMusicList(List<MusicData> musicFileList) {
		
		if(null == musicFileList) {
			
			mMusicFileList.clear();
			mPlayState = MusicPlayState.MP3_NOFILE;
			mCurPlayIndex = -1;
			return;
		}
		
		mMusicFileList = musicFileList;
		
		if(mMusicFileList.size() == 0 ) {
			mPlayState = MusicPlayState.MP3_NOFILE;
			mCurPlayIndex = -1;
			return;
		}
		
		switch (mPlayState) {
		
		case MusicPlayState.MP3_NOFILE:
			prepare(0);
			break;
        
		case MusicPlayState.MP3_INVALID:
			prepare(0);
			break;
		
		case MusicPlayState.MP3_PREPARED:
			prepare(0);
			break;
			
		case MusicPlayState.MP3_PLAYING:
			break;
		case MusicPlayState.MP3_PAUSE:			
			break;
			
		default:
			break;
		}
		
	}

	private boolean prepare(int index) {
		
		mCurPlayIndex = index;
		mMediaPlayer.reset();
		
		String path = mMusicFileList.get(index).mMusicPath;
		
		try {
			mMediaPlayer.setDataSource(path);
			mMediaPlayer.prepare();
			mPlayState = MusicPlayState.MP3_PREPARED;
			sendPlayStateBrocast();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mPlayState = MusicPlayState.MP3_INVALID;
			sendPlayStateBrocast();
			return false;
		} 
		
		return true;
	}

	
	public List<MusicData> getFileList() {
		
		return mMusicFileList;
	}
 
	public int getPlayState() {
		
		return mPlayState;
	}

	
	public boolean rePlay() {
		
		if(mPlayState == MusicPlayState.MP3_NOFILE || mPlayState == MusicPlayState.MP3_INVALID) {
			//没有文件或者文件非法直接返回
			return false;
		}
		
		mMediaPlayer.start();
		mPlayState = MusicPlayState.MP3_PLAYING;
		sendPlayStateBrocast();
		return true;
		
	}
	
	
	public boolean play(int index) {
		if(mPlayState == MusicPlayState.MP3_NOFILE) {
			return false;
		}
		
		if(mCurPlayIndex == index) {
			
			if(!mMediaPlayer.isPlaying()) {
				mMediaPlayer.start();
				mPlayState = MusicPlayState.MP3_PLAYING;
				sendPlayStateBrocast();
			}
			
			return true;
		}
		
		mCurPlayIndex = index ;
		if(!prepare(mCurPlayIndex)) {
			
			return false;
		}
		
		return rePlay();
	}
	
	public boolean pause() {
		
		if(mPlayState != MusicPlayState.MP3_PLAYING) {
			return false ;
		}
		
		mMediaPlayer.pause();
		mPlayState = MusicPlayState.MP3_PAUSE;
		sendPlayStateBrocast();
		return true;
	}
	
	public boolean stop() {
		if(mPlayState != MusicPlayState.MP3_PLAYING || mPlayState != MusicPlayState.MP3_PAUSE) {
			return false;
		}
		
		return prepare(mCurPlayIndex);
	}

	public boolean playNext() {
		if(mPlayState == MusicPlayState.MP3_NOFILE) {
			return false;
		}
		
		mCurPlayIndex++;
		mCurPlayIndex = reviceIndex(mCurPlayIndex);
		
		if(!prepare(mCurPlayIndex)) {
			return false;
		} 
		
		return rePlay();
	}

   public boolean playPre() {
	   if(mPlayState == MusicPlayState.MP3_NOFILE) {
		   return false;
	   }
	   
	   mCurPlayIndex--;
	   mCurPlayIndex = reviceIndex(mCurPlayIndex);
	   
	   if(!prepare(mCurPlayIndex)) {
		   return false;
	   }
	   
	   return rePlay();
   }

   
   public boolean seekTo(int rate) {
	   if(mPlayState == MusicPlayState.MP3_NOFILE || mPlayState == MusicPlayState.MP3_INVALID) {
		   return false;
	   }
	   
	   int r = reviceSeekValue(rate);
	   int time = mMediaPlayer.getDuration();
	   int curTime = (int) ((float)r/100 * time) ;
	   mMediaPlayer.seekTo(curTime);
	   return true;
   }

   public int getCurPosition() {
	   
	   if(mPlayState == MusicPlayState.MP3_PLAYING || mPlayState == MusicPlayState.MP3_PAUSE) {
		   
		   return mMediaPlayer.getCurrentPosition();
	   }
	   return 0;
   }

   public int getDuration() {
	   
	   if(mPlayState == MusicPlayState.MP3_INVALID || mPlayState == MusicPlayState.MP3_NOFILE) {
		   return 0;
	   }
	   
	   return mMediaPlayer.getDuration();
   }

   public void setPlayMode(int mode) {
	   
	   switch (mode) {
		case MusicPlayMode.MP3_LIST_LOOP_PLAY:
		case MusicPlayMode.MP3_ORDER_PLAY:
		case MusicPlayMode.MP3_RANDOM_PLAY:
		case MusicPlayMode.MP3_SINGLE_LOOP_PLAY:
			mPlayMode = mode;
			break;
	}
   }
   
   public int getPlayMode() {
	   return mPlayMode;
   }
	   
	private int reviceSeekValue(int rate) {

		if(rate < 0) {
			rate = 0;
		}
		if (rate > 100) {
			rate = 100;
		}
		return rate;
	}
	
	private int reviceIndex(int index) {
		if(index < 0) {
			index = mMusicFileList.size() - 1;
		}
		if(index >= mMusicFileList.size()) {
			index = 0;
		}
		return index;
	}

	private void sendPlayStateBrocast() {

		if(null != context) {
			Intent intent = new Intent(BROCAST_NAME);
			intent.putExtra(MusicPlayState.PLAY_STATE_NAME, mPlayState);
			intent.putExtra(MusicPlayState.PLAY_MUSIC_INDEX, mCurPlayIndex);
			
			if(mPlayState != MusicPlayState.MP3_NOFILE) {
				
				Bundle bundle = new Bundle();
				MusicData data = mMusicFileList.get(mCurPlayIndex);
				bundle.putParcelable(MusicData.KEY_MUSIC_DATA, data);
				intent.putExtra(MusicData.KEY_MUSIC_DATA, bundle);
			}
			
			context.sendBroadcast(intent);
		}
	}
	
	public void exit() {
		
		mMediaPlayer.reset();
		mMusicFileList.clear();
		mCurPlayIndex = -1;
		mPlayState = MusicPlayState.MP3_NOFILE;
		
	}
	
	
    /**
     * MediaPlayer音乐文件播放完毕
     */
	@Override
	public void onCompletion(MediaPlayer mp) {

		switch (mPlayMode) {
		//列表循环
		case MusicPlayMode.MP3_LIST_LOOP_PLAY: {
			
			playNext();
		}			
			break;
			
		//顺序播放
		case MusicPlayMode.MP3_ORDER_PLAY: {
			
			if(mCurPlayIndex != mMusicFileList.size()-1) {
				playNext();
			}else {
				prepare(mCurPlayIndex);
			}
		}
			break;
		
		//随机播放
		case MusicPlayMode.MP3_RANDOM_PLAY: {
		 
			int index = getRandomIndex();
			if(index == -1) {
				mCurPlayIndex++;
			}else{
				mCurPlayIndex = index;
			}
			
			mCurPlayIndex = reviceIndex(mCurPlayIndex);
			if(prepare(mCurPlayIndex)) {
				rePlay();
			}
		}			
			break;
			
		//单曲循环
		case MusicPlayMode.MP3_SINGLE_LOOP_PLAY:{
			play(mCurPlayIndex);
		}
			break;
	    default :
	    	prepare(mCurPlayIndex);
	    	break;
		}
	}
	
	
	private int getRandomIndex() {
		int size = mMusicFileList.size();
		if(size == 0) {
			return -1;
		}
		
		return Math.abs(mRandom.nextInt() % size);

	}


	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		return false;
	}
}
